import React from 'react';
import Popup from '../Popup';
import ListItem from './ListItem';

const Picker = React.forwardRef((props, ref) => {
    const {
        title,
        multiple = false,
        children,
        data,
        value,
        onChange,
        placeholder = '请选择',
        splitter = ',',
        ...rest
    } = props;
    const [current, setCurrent] = React.useState(value);

    React.useEffect(() => {
        if (value !== current) {
            setCurrent(value);
        }
    }, [value]);

    const getExtra = () => {
        if (data && Array.isArray(data) && value && Array.isArray(value)) {
            return data
                .filter(item => value.includes(item.value))
                .map(item => item.label)
                .join(splitter);
        }
        return '';
    };

    return (
        <Popup
            ref={ref}
            title={title}
            content={data?.map(item => (
                <ListItem
                    key={item?.value}
                    selected={current && Array.isArray(current) && item?.value && current.includes(item?.value)}
                    onClick={() => {
                        if (multiple && item?.value) {
                            if (current?.includes(item.value)) {
                                setCurrent(current?.filter(it => it !== item.value));
                            } else {
                                setCurrent([...(current || []), item?.value]);
                            }
                        } else {
                            setCurrent([item?.value]);
                        }
                    }}
                >
                    {item?.label}
                </ListItem>
            ))}
            onSubmit={() => {
                if (onChange) {
                    onChange(current);
                }
            }}
            afterClose={() => setCurrent(value)}
            {...rest}
        >
            {React.cloneElement(children, {
                extra: getExtra() || placeholder
            })}
        </Popup>
    );
});

export default Picker;
